package com.alinesno.cloud.gateway.admin.proxy.socket;

import java.util.HashMap;
import java.util.Map;

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alinesno.cloud.gateway.admin.entity.GateBusinessServerEntity;
import com.alinesno.cloud.gateway.admin.proxy.BaseProxy;
import com.alinesno.cloud.gateway.core.dispather.BaseDispather;
import com.alinesno.cloud.gateway.core.dispather.mina.MinaSocketProxyFactory;
import com.alinesno.cloud.gateway.core.dispather.mina.bean.BusinessServerBean;
import com.alinesno.cloud.gateway.core.dispather.mina.bean.MessageBean;
import com.alinesno.cloud.gateway.core.dispather.mina.bean.MessageBuilder;

/**
 * Socket转成Http代理转发
 * 
 * @author WeiXiaoJin
 * @since 2020年1月31日 下午19:45:08
 */
@Service(BaseDispather.SOCKET_PROXY_PREFIX + BaseDispather.SOCKET_PROXY_HTTP)
public class MinaSocketToHttpProxy extends BaseProxy implements MinaSocketProxyFactory {

	private static final Logger log = LoggerFactory.getLogger(MinaSocketToHttpProxy.class);
	private RestTemplate restTemplate = new RestTemplate();

	@Override
	protected MessageBean proxy(BusinessServerBean server, IoSession session, MessageBean message, GateBusinessServerEntity e, String clientIP) {
		log.debug("socket转成http代理转发....");

		String proxyUrl = e.getForwardUrl();

		Map<String, Object> map = new HashMap<>();
		map.put("data", message);

		ResponseEntity<Void> response = restTemplate.postForEntity(proxyUrl, map, Void.class);
		if (response.getStatusCode() == HttpStatus.OK) {
			log.debug("Request Successful");
		} else {
			log.debug("Request Failed");
		}

		return MessageBuilder.ok();
	}

}
